//引入扩展组件
Ext.Loader.setConfig({enabled: true});

Ext.Loader.setPath('Ext.ux', '../ExtJS4.2/ux/');

Ext.require([
    'Ext.data.*',
    'Ext.grid.*',
    'Ext.util.*',
    'Ext.tip.QuickTipManager',
    'Ext.ux.data.PagingMemoryProxy',
    'Ext.ux.ProgressBarPager'
]);
Ext.onReady(function() {
	//var AllSelectedRecords = []; //全局数组，保存分页选中数据
	
	Ext.define("DeptModel", {
	    extend: "Ext.data.TreeModel",
	    fields: [
	        "dept_id", "dept_name", "dept_status","description"
	    ]
	});
	var store = Ext.create("Ext.data.TreeStore",{
    	model: "DeptModel",
    	// 根节点的参数是parentId
        //nodeParam : 'deptParentId',
        // 根节点的参数值是0
        //defaultRootId : 0,
        proxy:{ 
            type:'ajax',  
            url:'/dept/showDept',
            reader : {
                type : 'json',
                root : 'children'//数据  
            }
        }
    });
    var columns = [{xtype: 'rownumberer'},
           {
		        text: '编号',
		        flex: 1,
		        dataIndex: 'dept_id',
		        hidden: true,
		        sortable: true
    		},{
                xtype: 'treecolumn', //this is so we know which column will show the tree
                text: '名称',
                width:'50%',
                flex: 3,
                sortable: true,
                dataIndex: 'dept_name'
            },{
                text: '状态',
                flex: 0.4,
                width:'2%',
                dataIndex: 'dept_status',
                sortable: true,renderer:function(value){  
                    if(value=='AVAILABLE'){  
                        return "<span style='color:green;font-weight:bold';>正常</span>";  
                    } else {  
                        return "<span style='color:red;font-weight:bold';>停用</span>";  
                    }
                }
            },{
                text: '描述',
                flex: 3,
                width:'50%',
                dataIndex: 'description',
                sortable: true
            }];
    var fields = [  
                  {name:'dept_id'}, //mapping:0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
                  {name:'dept_name'},  
                  {name:'dept_status'},  
                  {name:'description'}
                ];
    //var sm = Ext.create('Ext.selection.CheckboxModel');
	var tree = Ext.create('Ext.tree.Panel', {
	    renderTo: Ext.getBody(),
	    rootVisible: false,
	    region: 'center',
	    //selModel: sm,
	    loadMask:true, //显示遮罩和提示功能,即加载Loading……  
	    columnLines:false, //列的边框
	    border: false,
	    forceFit:true, //自动填满表格 
	    rowLines:true, //设置为false则取消行的框线样式
	    columns: columns,
	    store:store,
	    dockedItems: [{
        	xtype:'toolbar',
        	dock:'top',
        	displayInfo: true,
        	items:[{
        	    	   xtype:'button',
        	    	   id:'helpMenu',
        	    	   text: '帮助',
        	    	   iconCls:'Help',
        	    	   hidden:true,
        	    	   listeners: {
        	    		   click:function(){
        	    			   Ext.create('Ext.window.Window', {
        	    					layout:'fit',
        	    					width: 500,
        	    					height:350,
        	    					closeAction:'hide',
        	    					modal: true,
        	    					plain: true,
        	    					maximizable: true,
        	    					title: "帮助",
        	    					iconCls: "Help",
        	    					html:'<h3 align="center">部门管理功能的使用</h3>&nbsp;&nbsp;'+
        	    						'&nbsp;&nbsp;&nbsp;&nbsp;在部门列表中点击右键操作，'+
        	    						'选择相应的菜单内容，每列前面的勾<font color="blue" style="font-weight:bold">需要勾上</font>'+
        	    						'再进行操作，操作中不要忘了保存。<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;请注意部门'+
        	    						'列表中添加、删除、修改、分配<font color="red" style="font-weight:bold">不支持多选</font>，'+
        	    						'如果多选，那么系统会自动取最后一次勾选的为准!</p>'
        	    				}).show();
        	    		   }
        	    	   }
        	       },{
        	    	   xtype:'splitbutton',
        	    	   text: '管理部门',
        	    	   iconCls:'Userhome',
        	    	   menu: Ext.create('Ext.menu.Menu', {
        	    		   items: [{
		        	    	   id:'addUpDeptNode',
		        	    	   text: '添加上级部门',
		        	    	   disabled:true,
		        	    	   iconCls:'Arrowup',
		        	    	   hidden:true,
		        	    	   listeners: {
		        	    		   click:function(){
		        	    			   addDept();
		        	    		   }
		        	    	   }
		        	       },{
		        	    	   id:'addSameDeptNode',
		        	    	   disabled:true,
		        	    	   text: '添加同级部门',
		        	    	   iconCls:'Arrowew',
		        	    	   hidden:true,
		        	    	   listeners: {
		        	    		   click:function(){
		        	    			   addSameDept();
		        	    		   }
		        	    	   }
		        	       },{
		        	    	   id:'addDownDeptNode',
		        	    	   text: '添加下级部门',
		        	    	   iconCls:'Arrowdown',
		        	    	   hidden:true,
		        	    	   disabled:true,
		        	    	   listeners: {
		        	    		   click:function(){
		        	    			   addChildDept();
		        	    		   }
		        	    	   }
		        	       },{
		        	    	   id:'editDeptNode',
		        	    	   text: '编辑当前部门',
		        	    	   disabled:true,
		        	    	   hidden:true,
		        	    	   iconCls:'Arrowswitch',
		        	    	   listeners: {
		        	    		   click:function(){
		        	    			   editDept();
		        	    		   }
		        	    	   }
		        	       },{
		        	    	   id:'delNode',
		        	    	   text: '删除部门',
		        	    	   disabled:true,
		        	    	   iconCls:'Arrowout',
		        	    	   hidden:true,
		        	    	   listeners: {
		        	    		   click:function(){
		        	    			   Ext.MessageBox.confirm("删除提示", "确定要删除当前节点吗？如果此节点下有子节点，那么子节点也会被删除",function(btn){
		        	   					if(btn=='yes'){
		        	   						var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
		        	   						if(deptId==1){
		        	   							Ext.Msg.alert('删除节点失败', '我是系统管理总部，我不可被删除，请慎重考虑！');
		        	   						}else{
		        	   							Ext.Ajax.request({
			        	   							  url: '/dept/deleteDept?deptId='+deptId,
			        	   							  success:function(request){
			        	   								  Ext.Msg.alert('删除节点成功', '删除节点及子节点成功');
			        	   								  store.reload();
			        	   							  },
			        	   							  failure:function(res){
			        	   								  var respText = Ext.decode(res.responseText);
			        	   								  Ext.Msg.alert('删除节点失败', respText.message+"("+respText.code+")");
			        	   							  }
			        	   						  });
		        	   							}
		        	   						}    
		        	   					}); 
		        	   				} 
		        	    	   }
		        	       }]
        	    	   })
        	       },{
        	    	   xtype:'button',
        	    	   id:'manRole',
        	    	   text: '分配角色',
        	    	   disabled:true,
        	    	   hidden:true,
        	    	   iconCls:'Chartorganisation',
        	    	   listeners: {
        	    		   click:function(){
        	    			   manDept();
        	    		   }
        	    	   }
        	       },{
        	    	   xtype:'button',
        	    	   id:'refreshDept',
        	    	   text: '刷新',
        	    	   iconCls:'Arrowrefresh',
        	    	   hidden:true,
        	    	   listeners: {
        	    		   click:function(){
	        	               	store.reload();
        	    		   }
        	    	   }
        	       }]
        }]
	});
	
	//监听表格
    tree.getSelectionModel().on({
        selectionchange: function(sm, selections) {
            if (selections.length) {
            	Ext.getCmp('addUpDeptNode').setDisabled(false);
            	Ext.getCmp('addSameDeptNode').setDisabled(false);
            	Ext.getCmp('addDownDeptNode').setDisabled(false);
            	Ext.getCmp('editDeptNode').setDisabled(false);
            	Ext.getCmp('delNode').setDisabled(false);
            	Ext.getCmp('manRole').setDisabled(false);
            } else {
            	Ext.getCmp('addUpDeptNode').setDisabled(true);
            	Ext.getCmp('addSameDeptNode').setDisabled(true);
            	Ext.getCmp('addDownDeptNode').setDisabled(true);
            	Ext.getCmp('editDeptNode').setDisabled(true);
            	Ext.getCmp('delNode').setDisabled(true);
            	Ext.getCmp('manRole').setDisabled(true);
            }
        }
    });
	
	//tree.expandAll();//1.这里设置展开所有节点2.java代码里控制展开与否
	//增加上级部门
	var form = Ext.create('Ext.form.Panel', {
		 border : false,
		 width: 450,
		 defaults:{  
			 margin:'10 20 0 20',
	         anchor: '100%',
	         width:280 
	     }, 
		 defaultType: 'textfield',
		 items: [{
				fieldLabel: '部门名',
				name: 'dept_name',
				maxLengthText :'部门名长度不能超过20',  
	            maxLength : 20,
				allowBlank:false,
				inputType: 'dept_name'
			},{
				xtype: 'combobox',
				fieldLabel: '部门状态',
				name: 'dept_status',
				allowBlank:false,
				queryMode: 'local',
			    displayField: 'name',
			    valueField: 'abbr',
			    editable:false,
				store: Ext.create('Ext.data.Store', {
					 fields: ['abbr', 'name'],
					    data : [
					        {"abbr":"AVAILABLE", "name":"正常"},
					        {"abbr":"DISABLED", "name":"禁用"}
					    ]
	             })
			},{
				fieldLabel: '描述',
				xtype: 'textareafield',
				name: 'description',
				height:270,
				inputType: 'description'
			}
			],
			buttons: [{
				text: '保&nbsp;存',
				handler: function() {
					if(form.form.isValid()) {
						var deptFatherId = tree.getSelectionModel().getLastSelected().raw.dept_father_id;
						var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
						form.form.submit({
							url: '/dept/addPartenrDept',
							method: 'POST',
							params:{deptFatherId:deptFatherId,deptId:deptId},
							success: function(form, action) {
								Ext.Msg.alert('保存成功', '增加上级部门成功！');
								win.hide();
								store.load(); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					} else {
						Ext.Msg.alert('系统提示', '请填写完整再提交！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					win.hide();
				}
			}]
	});
	
	//增加同级部门
	var sameform = Ext.create('Ext.form.Panel', {
		 border : false,
		 width: 450,
		 defaults:{  
			 margin:'10 20 0 20',
	         anchor: '100%',
	         width:280
	     }, 
		 defaultType: 'textfield',
		 items: [{
				fieldLabel: '部门名',
				name: 'dept_name',
				maxLengthText :'部门名长度不能超过20',  
	            maxLength : 20,
				allowBlank:false,
				inputType: 'dept_name'
			},{
				xtype: 'combobox',
				fieldLabel: '部门状态',
				name: 'dept_status',
				allowBlank:false,
				queryMode: 'local',
			    displayField: 'name',
			    valueField: 'abbr',
			    editable:false,
				store: Ext.create('Ext.data.Store', {
					 fields: ['abbr', 'name'],
					    data : [
					        {"abbr":"AVAILABLE", "name":"正常"},
					        {"abbr":"DISABLED", "name":"禁用"}
					    ]
	             })
			},{
				fieldLabel: '描述',
				xtype: 'textareafield',
				height:270,
				name: 'description',
				inputType: 'description'
			}
			],
			buttons: [{
				text: '保&nbsp;存',
				handler: function() {
					if(sameform.form.isValid()) {
						var deptFatherId = tree.getSelectionModel().getLastSelected().raw.dept_father_id;
						var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
						sameform.form.submit({
							url: '/dept/addSameDept',
							method: 'POST',
							params:{deptFatherId:deptFatherId,deptId:deptId},
							success: function(form, action) {
								Ext.Msg.alert('保存成功', '增加同级部门成功！');
								samewin.hide();
								store.load(); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					} else {
						Ext.Msg.alert('系统提示', '请填写完整再提交！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					samewin.hide();
				}
			}]
	});
	
	//增加下级部门
	var childform = Ext.create('Ext.form.Panel', {
		 border : false,
		 width: 450,
		 defaults:{  
			 margin:'10 20 0 20',
	         anchor: '100%',
	         width:280
	     }, 
		 defaultType: 'textfield',
		 items: [{
				fieldLabel: '部门名',
				name: 'dept_name',
				maxLengthText :'部门名长度不能超过20',  
	            maxLength : 20,
				allowBlank:false,
				inputType: 'dept_name'
			},{
				xtype: 'combobox',
				fieldLabel: '部门状态',
				name: 'dept_status',
				editable:false,
				allowBlank:false,
				queryMode: 'local',
			    displayField: 'name',
			    valueField: 'abbr',	
				store: Ext.create('Ext.data.Store', {
					 fields: ['abbr', 'name'],
					    data : [
					        {"abbr":"AVAILABLE", "name":"正常"},
					        {"abbr":"DISABLED", "name":"禁用"}
					    ]
	             })
			},{
				fieldLabel: '描述',
				xtype: 'textareafield',
				name: 'description',
				height:270,
				inputType: 'description'
			}
			],
			buttons: [{
				text: '保&nbsp;存',
				handler: function() {
					if(childform.form.isValid()) {
						var deptFatherId = tree.getSelectionModel().getLastSelected().raw.dept_father_id;
						var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
						childform.form.submit({
							url: '/dept/addChildDept',
							method: 'POST',
							params:{deptFatherId:deptFatherId,deptId:deptId},
							success: function(form, action) {
								Ext.Msg.alert('保存成功', '增加下级部门成功！');
								childwin.hide();
								store.load(); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					} else {
						Ext.Msg.alert('系统提示', '请填写完整再提交！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					childwin.hide();
				}
			}]
	});
	
	//编辑部门
	var editform = Ext.create('Ext.form.Panel', {
		 border : false,
		 width: 450,
		 defaults:{  
	         margin:'10 20 0 20',
	         anchor: '100%',
	         width:280
	     }, 
		 defaultType: 'textfield',
		 items: [{
				fieldLabel: 'ID',
				name: 'dept_id',
				hidden:true
			},{
				fieldLabel: '部门名',
				name: 'dept_name',
				maxLengthText :'部门名长度不能超过20',  
	            maxLength : 20,
				allowBlank:false,
				inputType: 'dept_name'
			},{
				xtype: 'combobox',
				fieldLabel: '部门状态',
				name: 'dept_status',
				allowBlank:false,
				editable:false,
				queryMode: 'local',
			    displayField: 'name',
			    valueField: 'abbr',	
				store: Ext.create('Ext.data.Store', {
					 fields: ['abbr', 'name'],
					    data : [
					        {"abbr":"AVAILABLE", "name":"正常"},
					        {"abbr":"DISABLED", "name":"禁用"}
					    ]
	             })
			},{
				fieldLabel: '描述',
				xtype: 'textareafield',
				name: 'description',
				height:270,
				inputType: 'description'
			}
			],
			buttons: [{
				id:'saveDept',
				text: '保&nbsp;存',
				handler: function() {
					if(editform.form.isValid()) {
						editform.form.submit({
							url: '/dept/editDept',
							method: 'POST',
							success: function(form, action) {
								Ext.Msg.alert('编辑成功', '编辑部门成功！');
								editwin.hide();
								store.load(); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '数据保存中，请稍候...'
						});
					} else {
						Ext.Msg.alert('系统提示', '请填写完整再提交！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					editwin.hide();
				}
			}]
	});
	
	//增加上级部门
	var win = Ext.create('Ext.window.Window', {
		layout:'fit',
		width: 450,
		height:450,
		closeAction:'hide',
		modal: true,
		plain: true,
		title: "添加上级部门",
		iconCls: "Vcard",
		items: [form]
	});
	
	//增加同级部门
	var samewin = Ext.create('Ext.window.Window', {
		layout:'fit',
		width: 450,
		height:450,
		closeAction:'hide',
		modal: true,
		plain: true,
		title: "添加同级部门",
		iconCls: "Vcard",
		items: [sameform]
	});
	//增加下级部门
	var childwin = Ext.create('Ext.window.Window', {
		layout:'fit',
		width: 450,
		height:450,
		closeAction:'hide',
		modal: true,
		plain: true,
		title: "添加下级部门",
		iconCls: "Vcard",
		items: [childform]
	});
	//编辑部门
	var editwin = Ext.create('Ext.window.Window', {
		layout:'fit',
		width: 450,
		height:450,
		closeAction:'hide',
		modal: true,
		plain: true,
		title: "编辑部门",
		iconCls: "Vcard",
		items: [editform]
	});
	function addDept() {
		form.form.reset();
		win.show();
	}
	function addSameDept() {
		sameform.form.reset();
		samewin.show();
	}
	function addChildDept() {
		childform.form.reset();
		childwin.show();
	}
	function editDept() {
		var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
		if(deptId==1){
			Ext.Msg.alert('编辑部门', '我是系统管理总部，不可被编辑！');
		}else{
			editform.form.reset();
			editwin.show();
			editform.form.load({
				url: '/dept/loadDept?deptId=' + deptId,
				method:'POST',
				waitMsg : '正在载入数据...',
				reader: Ext.create('Ext.data.JsonReader', {
					 type  : 'json',
					 root  : 'data'
				 },fields),
				success : function(form,action) {},
				failure : function(form,action) {
					Ext.Msg.alert('编辑部门', '数据读取失败');
					editwin.hide();
				}
			});
		}
		
	}
	// 定义右键菜单
	var contextMenu = Ext.create("Ext.menu.Menu",{
		width: 100,
	    plain: true,
	    floating: true,  // usually you want this set to True (default)
	    renderTo: Ext.getBody(),  // usually rendered by it's containing component
		items : [{
			id:'rightAddParternDept',
			text : '添加上级部门',
			iconCls:'Arrowup',
			hidden:true,
			handler : function(){
				addDept();
			}
		},{
			id:'rightAddSameDept',
			text : '添加同级部门',
			iconCls:'Arrowew',
			hidden:true,
			handler : function(){
				addSameDept();
			}
		},{
			id:'rightAddDownDept',
			text : '添加下级部门',
			iconCls:'Arrowdown',
			hidden:true,
			handler : function(){
				addChildDept();
			}
		},{
			id:'rightEditDept',
			text : '编辑部门',
			iconCls:'Arrowswitch',
			hidden:true,
			handler : function(){
				editDept();
			}
		},{
			id:'rightDelDept',
			text : '删除部门',
			iconCls:'Arrowout',
			hidden:true,
			handler : function(){
				Ext.MessageBox.confirm("删除提示", "确定要删除当前节点吗？如果此节点下有子节点，那么子节点也会被删除",function(btn){
					if(btn=='yes'){
						var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
						if(deptId==1){
   							Ext.Msg.alert('删除节点失败', '我是系统管理总部，我不可被删除，请慎重考虑！');
   						}else{
   							Ext.Ajax.request({
  							  url: '/dept/deleteDept?deptId='+deptId,
  							  success:function(request){
  								  Ext.Msg.alert('删除节点成功', '删除节点及子节点成功');
  								  store.reload();
  							  },
  							  failure:function(res){
  								  var respText = Ext.decode(res.responseText);
  								  Ext.Msg.alert('删除节点失败', respText.message+"("+respText.code+")");
  							  }
  						  });
   						}
					}    
				}); 
			}  
		},{
			id:'rightManRole',
			text : '分配角色',
			iconCls:'Chartorganisation',
			hidden:true,
			handler : function(){
				manDept();
			}  
		},{
			id:'rightRefresh',
			text : '刷新',
			iconCls:'Arrowrefresh',
			hidden:true,
			handler : function(){
				store.reload();
			}  
		}] 
	});
	tree.on('itemcontextmenu', treeContextHandler);
	tree.on("itemdblclick",function(tree, row){
		editDept(); 
    });
	//亮点功能
    //判断页面按钮是否有权限
    //默认全部禁用，取出数据对比，如果分配了则显示使用，否则禁用
    	Ext.Ajax.request({
            url: '/menuPer/getMenuPer',
            timeout: 30000,
          	success: function(response,options) {
          		var respText = Ext.JSON.decode(response.responseText);
          		if(respText.code == 'OK') {
          			var rec = respText.data;
          			for(var i=0; i<rec.length; i++){
          				if(rec[i].kind=='helpMenu'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('helpMenu').hide();
          					}else{
          						Ext.getCmp('helpMenu').show();
          					}
          				}
          				if(rec[i].kind=='addUpDeptNode'){
          					var addUserV = rec[i].value;
          					
          					if(addUserV =='true'){
          						Ext.getCmp('addUpDeptNode').hide();
          					}else{
          						Ext.getCmp('addUpDeptNode').show();
          					}
          				}
          				if(rec[i].kind=='addSameDeptNode'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('addSameDeptNode').hide();
          					}else{
          						Ext.getCmp('addSameDeptNode').show();
          					}
          				}
          				if(rec[i].kind=='addDownDeptNode'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('addDownDeptNode').hide();
          					}else{
          						Ext.getCmp('addDownDeptNode').show();
          					}
          				}
          				if(rec[i].kind=='editDeptNode'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('editDeptNode').hide();
          					}else{
          						Ext.getCmp('editDeptNode').show();
          					}
          				}
          				if(rec[i].kind=='delNode'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('delNode').hide();
          					}else{
          						Ext.getCmp('delNode').show();
          					}
          				}
          				if(rec[i].kind=='manRole'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('manRole').hide();
          					}else{
          						Ext.getCmp('manRole').show();
          					}
          				}
          				if(rec[i].kind=='refreshDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('refreshDept').hide();
          					}else{
          						Ext.getCmp('refreshDept').show();
          					}
          				}
          				if(rec[i].kind=='rightAddParternDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightAddParternDept').hide();
          					}else{
          						Ext.getCmp('rightAddParternDept').show();
          					}
          				}
          				if(rec[i].kind=='rightAddSameDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='rightAddSameDept'){
          						Ext.getCmp('rightAddSameDept').hide();
          					}else{
          						Ext.getCmp('rightAddSameDept').show();
          					}
          				}
          				if(rec[i].kind=='rightAddDownDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightAddDownDept').hide();
          					}else{
          						Ext.getCmp('rightAddDownDept').show();
          					}
          				}
          				if(rec[i].kind=='rightEditDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightEditDept').hide();
          					}else{
          						Ext.getCmp('rightEditDept').show();
          					}
          				}
          				if(rec[i].kind=='rightDelDept'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightDelDept').hide();
          					}else{
          						Ext.getCmp('rightDelDept').show();
          					}
          				}
          				if(rec[i].kind=='rightManRole'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightManRole').hide();
          					}else{
          						Ext.getCmp('rightManRole').show();
          					}
          				}
          				if(rec[i].kind=='rightRefresh'){
          					var addUserV = rec[i].value;
          					if(addUserV =='true'){
          						Ext.getCmp('rightRefresh').hide();
          					}else{
          						Ext.getCmp('rightRefresh').show();
          					}
          				}
          			}
          		}else{
          			console.info("数据加载失败了。。");
          		}
          	},
          	failure: function(response,options) {
          		console.info("数据加载失败了。。");
          	}
    });
	// 绑定节点右键菜单功能
	function treeContextHandler(view, record, item, index, event, options) {
		event.preventDefault();//一说是组织浏览器的默认右键事件，二说是防止两次出现右键画面（怎么可能出现两次）
		contextMenu.showAt(event.getXY());//显示右键菜单
	}
	// 整体架构容器
	Ext.create("Ext.container.Viewport", {
		layout : 'border',
		autoHeight: true,
		border: false,
		items : [tree]
	});
	
	function manDept(){
		var columns = [
	                   {xtype: 'rownumberer'},
	                   {header:'编号',dataIndex:'role_id',hidden: true},
	                   {header:'是否选中',dataIndex:'selected',hidden: true},
	                   {header:'角色名称',dataIndex:'role_name'},
	                   {header:'角色状态',dataIndex:'status',renderer:function(value){  
	                       if(value=='DISABLED'){  
	                           return "<span style='color:red;font-weight:bold';>禁用</span>";  
	                       } else {
	                           return "<span style='color:green;font-weight:bold';>正常</span>";  
	                       }
	           			}},
	                   {header:'角色描述',dataIndex:'description'}
	               ];
		
	    store = Ext.create("Ext.data.Store",{
	    	autoLoad : true,
	        proxy:{  
	            type:'ajax',  
	            url:'/deptRole/showRoles',  
	            reader:{  
	                type:'json',  
	                totalProperty:'total',  
	                root:'data',  
	                idProperty:'id'  
	            }  
	        },  
	        fields:[  
	           {name:'role_id'}, //mapping:0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
	           {name:'role_name'},  
	           {name:'status'},
	           {name:'description'},
	           {name:'selected'}
	        ],
	        listeners: {  
	            'beforeload': function (store, op, options) {
	                var params = {
	                    //参数  
	                	deptId:tree.getSelectionModel().getLastSelected().get('dept_id')
	                };
	                Ext.apply(store.proxy.extraParams, params);   
	            }
	        }  
	    });
	    var sm = Ext.create('Ext.selection.CheckboxModel');
	    var grid = Ext.create("Ext.grid.Panel",{
	    	region: 'center',
	    	border: false,
	    	store: store,
	    	selModel: sm,
	        columns: columns,
	        region: 'center', //框架中显示位置，单独运行可去掉此段
	        loadMask:true, //显示遮罩和提示功能,即加载Loading……  
	        forceFit:true, //自动填满表格  
	        columnLines:false, //列的边框
	        rowLines:true
	    });
	    //数据排序
	    store.sort('create_time','asc');
	    grid.store.on('load',function(store, records, options){
        	sm.clearSelections();
        	var arr = new Array();
        	Ext.each(records, function(rec,index) {
            	if (rec.get('selected')) {
            		arr.push(rec);
            	}
        	});
        	grid.getSelectionModel().select(arr);
        });
	    //分页保持选中,暂时不做此方案，影响下一条部门数据的选中与否状态
	    /*store.on({
	    	load: function (me, records, success, opts) {
	            if (!success || !records || records.length == 0){
	            	return;
	            }
	            //根据全局的选择，初始化选中的列
	            var selModel = grid.getSelectionModel();
	            Ext.Array.each(AllSelectedRecords, function () {
	                for (var i = 0; i < records.length; i++) {
	                    var record = records[i];
	                    if (record.get("role_id") == this.get("role_id")) {
	                        selModel.select(record, true, true);    //选中record，并且保持现有的选择，不触发选中事件
	                    }
	                }
	            });
	        }
	    });
	    grid.on({
	    	select: function (me, record, index, opts) {
	            AllSelectedRecords.push(record);
	        },
	        deselect: function (me, record, index, opts) {
	            AllSelectedRecords = Ext.Array.filter(AllSelectedRecords, function (item) {
	                return item.get("role_id") != record.get("role_id");
	            });
	        }
	    });*/
		var treewin =Ext.create('Ext.window.Window', {
			layout:'fit',
			width: 650,
			height:400,
			closeAction:'hide',
			maximizable: true,
			modal: true,
			plain: true,
			title: "分配角色",
			iconCls: "Vcard",
			items: [grid],
		    tbar: [{
	            text: '保存',
	            iconCls:'Bulletdisk',
	            scope: this,
	            handler: function(){
	            	var roleIds = "";
	            	var rec = grid.getSelectionModel().selected.items;
	            	var deptId = tree.getSelectionModel().getLastSelected().raw.dept_id;
	            	/*Ext.each(rec ,function(node){
	            		console.info("node:"+node.menu_id);
	            	});*/
	            	
	            	for(var i=0; i<rec.length; i++){
	            		if(i!=rec.length-1){
	            			roleIds +=rec[i].raw.role_id+',';
	            		}else{
	            			roleIds += rec[i].raw.role_id;
	            		}
	            	}
	            	//alert("部门ID:"+deptId+",角色ID集合:"+roleIds);
	            	Ext.Ajax.request({
						url: '/deptRole/addDeptRole?deptId='+deptId+"&roleIds="+roleIds,
						success: function(response,options) {
							var respText = Ext.JSON.decode(response.responseText);
							if(respText.code != 'OK') {
								Ext.Msg.alert('分配失败', respText.message + "（" + respText.code + "）");
							} else {
								Ext.Msg.alert('分配成功', '部门-角色关系保存成功！');
								treewin.hide();
							}
						},
						failure: function(response,options) {
							Ext.Msg.alert('分配失败', '部门-角色关系保存失败！');
						}
					});
	            }
	        },{
	        	text:'刷新',
	        	iconCls: "Arrowrefreshsmall",
	        	handler:function(){
	        		store.reload();
	        	}
	        }]
		}).show();
	}
});